---
--类名: EventManager.lua
--创建日期: 2015-12-7
--创建人: 陈小虎
--功能描述: 事件管理器
--修改内容: 以事件名字为key检索事件，返回handle
--修改日期:   2016-06-24
--修改人:     shunguo.chen
--修改备注: 
--

local string_find = string.find
local string_sub = string.sub

local EventManager = class("EventManager")

local handleIndex = 0

function EventManager:ctor()
	self._events = {}
	self._priorityEvents = {}
	self._isDirtyDict = {}
	self._eventNameDict ={}
end

--注册事件,防止事件冲突
function EventManager:regist(name)
	assert(name)
	local temp = self._eventNameDict[name]
	assert(type(temp)=="nil","event already exist "..name)
	self._eventNameDict[name]=name
end

---
-- @params eventName 事件名
-- @params listener 事件通知回调
-- @params node 绑定到node。node移除时，自动移除事件，
--		注意：同一node暂时只能绑定一个回调，多于一个会顶掉
--
function EventManager:on(eventName, listener, node)
	handleIndex = handleIndex + 1
	local handle = string.format("%d_%s", handleIndex, eventName)
	self._events[eventName] = self._events[eventName] or {}
	self._events[eventName][handle] = listener

	-- print("EventManager:on >>>", handle)

	if node and node.onNodeEvent then
	    node:onNodeEvent("exit", function(event)
            self:remove(handle)
	    end)
	end
	return handle
end

-- 移除指定handle
function EventManager:remove(handle)
	if nil == handle then return end
	-- print("EventManager.remove >>>", handle)

	local st = string_find(handle, "_")
	local eventName = string_sub(handle, st + 1)

	if self._events[eventName] then
		self._events[eventName][handle] = nil
	end
end

-- 移除eventName的所有监听
function EventManager:removeByName(eventName)
	if self._events[eventName] then
		self._events[eventName] = {}
	end
end

function EventManager:removeAll()
	self._events = {}
end

function EventManager:notify(eventName, ...)
	--print("EventManager:notify() eventName = " .. eventName)
	--dump(params, "EventManager:notify() params = ")
	local listeners = self._events[eventName]
	if listeners then
		for _, listener in pairs(listeners) do
			if listener then
				if DEBUG == 0 then
					local status,err = pcall(listener, eventName, ...)
					if err then
						release_print("<EventManager>",eventName,err)
					end
				else
					listener(eventName,...)
				end
			end
		end
	end
end

return EventManager